<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { reactive, watch, inject, Ref, ref, onBeforeUnmount, onMounted } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { Row } from '@/api/franchiser'
import {
  ElForm,
  ElFormItem,
  ElDivider,
  ElInput,
  ElRadioGroup,
  ElRadio,
  FormInstance,
  ElOption
} from 'element-plus'
import { searchSupplierCateApi } from '@/api/utils/search'
const { required } = useValidator()
const currentRow: Ref<Row> = inject('currentRow') as Ref<Row>
const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods
const formRef = ref<FormInstance>()
const from = ref({ money: '', type: 5, amount: '' })
const options = ref([])
const getSearchSupplierCateApi = async () => {
  const res = await searchSupplierCateApi({ field: 'name,id' })
  options.value = res.data.list
}
onMounted(() => {
  getSearchSupplierCateApi()
  from.value.amount = currentRow.value.money
  from.value.type = 5
  from.value.money = ''
})
const schema = reactive<FormSchema[]>([
  {
    field: '',
    label: '基础数据',
    component: 'Divider',
    colProps: { span: 28 },
    componentProps: {
      borderStyle: 'none',
      contentPosition: 'left'
    }
  },
  {
    field: 'name',
    label: '门店名称',
    component: 'Input',
    formItemProps: {
      rules: [required(), { min: 1, max: 30, message: '最多输入30个字符', trigger: 'blur' }]
    },
    componentProps: {
      placeholder: '请输入(最多30个字符)'
    }
  },
  {
    field: 'real_name',
    label: '门店负责人',
    component: 'Input',
    formItemProps: {
      rules: [required(), { min: 1, max: 10, message: '请输入最多支持10字符', trigger: 'blur' }]
    },
    componentProps: {
      placeholder: '请输入'
    }
  },
  {
    field: 'mobile',
    label: '联系电话',
    component: 'Input',
    formItemProps: {
      rules: [
        required(),
        { min: 11, max: 11, message: '请输入负责人联系电话', trigger: 'blur' },
        {
          pattern: /^[1][3,4,5,6,7,8,9][0-9]{9}$/,
          message: '请输入负责人联系电话',
          trigger: 'blur'
        }
      ]
    }
  },
  {
    field: 'address',
    label: '门店地址',
    component: 'Input',
    formItemProps: {
      rules: [required(), { min: 1, max: 100, message: '最多输入100个字符', trigger: 'blur' }]
    },
    componentProps: {
      placeholder: '请输入(最多100个字符)'
    }
  },
  {
    field: 'long',
    label: '仓库经度',
    component: 'Input',
    formItemProps: {
      rules: [
        {
          pattern:
            /^-?((0|[1-9]\d?|([1-9]\d(\.\d{1,6})?))|([1-9]\d{0,2}(\.\d{1,6})?)|([1-8]\d{0,2}(\.\d{1,6})?)|(90(\.0{1,6})?))$/,
          message: '请输入有效的经度',
          trigger: 'blur'
        }
      ]
    },
    componentProps: {
      placeholder: '请输入经度'
    }
  },
  {
    field: 'lat',
    label: '仓库纬度',
    component: 'Input',
    formItemProps: {
      rules: [
        {
          pattern:
            /^-?((0|[1-9]\d?|([1-9]\d(\.\d{1,6})?))|([1-9]\d{0,2}(\.\d{1,6})?)|([1-8]\d{0,2}(\.\d{1,6})?)|(90(\.0{1,6})?))$/,
          message: '请输入有效的纬度',
          trigger: 'blur'
        }
      ]
    },
    componentProps: {
      placeholder: '请输入纬度'
    }
  },
  {
    field: 'user_name',
    label: '户名',
    component: 'Input',
    componentProps: {
      placeholder: '请输入'
    }
  },
  {
    field: 'bank_type',
    label: '所属银行',
    component: 'Select',
    componentProps: {
      placeholder: '请选择',
      options: [
        {
          label: '中国银行',
          value: 1
        },
        {
          label: '建设银行',
          value: 2
        },
        {
          label: '工商银行',
          value: 3
        },
        {
          label: '农业银行',
          value: 4
        },
        {
          label: '交通银行',
          value: 5
        },
        {
          label: '招商银行',
          value: 6
        },
        {
          label: '浦发银行',
          value: 7
        },
        {
          label: '兴业银行',
          value: 8
        },
        {
          label: '民生银行',
          value: 9
        },
        {
          label: '光大银行',
          value: 10
        },
        {
          label: '广发银行',
          value: 11
        },
        {
          label: '华夏银行',
          value: 12
        },
        {
          label: '平安银行',
          value: 13
        },
        {
          label: '邮政储蓄银行',
          value: 14
        },
        {
          label: '其他',
          value: 15
        }
      ]
    }
  },
  {
    field: 'bank_branch',
    label: '开户行',
    component: 'Input',
    formItemProps: {
      rules: [{ min: 1, max: 100, message: '最多输入100个字符', trigger: 'blur' }]
    },
    componentProps: {
      placeholder: '请输入(最多100个字符)'
    }
  },
  {
    field: 'bank_no',
    label: '银行卡号',
    component: 'Input',
    formItemProps: {
      rules: [
        {
          pattern: /^[1-9]\d{9,29}$/,
          message: '请核对银行卡号',
          trigger: 'blur'
        }
      ]
    },
    componentProps: {
      placeholder: '请输入'
    }
  },
  {
    field: 'supplier_id',
    label: '所属经销商',
    component: 'Select',
    formItemProps: {
      rules: [{ required: true, message: '请选择所属经销商', trigger: 'blur' }]
    },
    componentProps: {
      placeholder: '请选择',
      options: options,
      slots: {
        default: (options) => {
          if (options.length) {
            return options?.map((v) => {
              return <ElOption key={v.id} label={v.name} value={v.id} />
            })
          } else {
            return null
          }
        }
      }
    }
  },
  {
    field: 'is_on_credit',
    label: '开启账期',
    component: 'Select',
    componentProps: {
      placeholder: '请输入',
      options: [
        {
          label: '是',
          value: 1
        },
        {
          label: '否',
          value: 2
        }
      ],
      on: {
        change: (val) => {
          isOnCredit(val)
        }
      }
    }
  }
])
// 账期
const isOnCredit = async (val) => {
  const index = schema.findIndex((item) => item.label === '账期(天)')
  if (index !== 1 && schema.length > 13) {
    schema.splice(index, 1)
  }
  if (val === 2 && index !== -1) {
    schema.splice(index, 1)
  }
  if (val == 1) {
    schema.push({
      field: 'credit_days',
      label: '账期(天)',
      component: 'Input',
      componentProps: {
        placeholder: '请输入'
      }
    })
  }
}
const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    const formDataList = {
      id: formData.id || '',
      name: formData.name || '',
      real_name: formData.real_name || '',
      mobile: formData.mobile || '',
      address: formData.address || '',
      money: from.value.money || '',
      type: from.value.type || 5,
      long: formData.long || '',
      lat: formData.lat || '',
      user_name: formData.user_name || '',
      bank_type: formData.bank_type || '',
      bank_branch: formData.bank_branch || '',
      bank_no: formData.bank_no || '',
      is_on_credit: formData.is_on_credit || 2,
      credit_days: formData.credit_days || '',
      supplier_id: formData.supplier_id || ''
    }
    return formDataList
  }
}

const reset = async () => {
  const elForm = await getElFormExpose()
  elForm?.resetFields()
}

watch(
  () => currentRow.value,
  (currentRow) => {
    if (!currentRow) return
    if (currentRow.is_on_credit) {
      isOnCredit(currentRow.is_on_credit)
    }
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

onBeforeUnmount(reset)

defineExpose({
  submit,
  reset
})
</script>

<template>
  <Form @register="formRegister" :schema="schema" />
  <ElForm ref="formRef" :model="from" label-width="auto" class="mt-[20px]">
    <ElDivider borderStyle="none" contentPosition="left">OMS设置</ElDivider>
    <div style="display: inline-block">
      <ElFormItem label="余额: " class="w-[300px] ml-36px" prop="amount">
        <ElInput v-model="from.amount" placeholder="请输入内容" disabled />
      </ElFormItem>
    </div>
    <div style="display: inline-block">
      <ElFormItem label="变动金额: " class="w-[480px] ml-36px" prop="money">
        <ElInput
          v-model="from.money"
          placeholder="如果变动金额类型为后台减少，请填写负数。如：-100"
        />
      </ElFormItem>
    </div>
    <div style="display: inline-block">
      <ElFormItem label="金额变动类型: " class="w-[300px] ml-36px" prop="type">
        <ElRadioGroup v-model="from.type">
          <ElRadio :label="5">后台增加</ElRadio>
          <ElRadio :label="6">后台减少</ElRadio>
        </ElRadioGroup>
      </ElFormItem>
    </div>
  </ElForm>
</template>
